package com.fly;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import com.fly.utils.LogMonitor;
import com.fly.utils.SQLParseUtil;

/*****
 * 界面操作展示类
 */
public class DataBaseUI extends JFrame implements Observer
{
    private static final long serialVersionUID = -5589543870438580897L;
    
    // 界面组件
    JPanel panel = new JPanel();
    
    JLabel logInfoLabel = new JLabel("日志信息");
    
    JTextArea logInfoTextArea = new JTextArea();
    
    // Excel目录
    JLabel excelLabel = new JLabel("Excel SQL 文件或目录");
    
    static JTextField excelDirText = new JTextField(null, 40);
    
    JButton excelDirBrowse = new JButton("请选择");
    
    // 以下为处理功能
    JButton export = new JButton(" 生 成 SQL ");
    
    JButton clearLog = new JButton(" 清 除 日 志 ");
    
    LogMonitor logMonitor = new LogMonitor();
    
    SQLParseUtil sqlParseUtil;
    
    // 构造函数
    public DataBaseUI()
    {
        // 加载图标
        URL imgURL = this.getClass().getResource("/img/icon.gif");
        if (imgURL != null)
        {
            Image image = Toolkit.getDefaultToolkit().createImage(imgURL);
            setIconImage(image);
        }
        setTitle("Excel 数据库定义表生成处理工具 V1.0");
        // 设置宽高
        setSize(900, 550);
        // 得到当前系统screenSize
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // 得到当前frameSize
        Dimension frameSize = this.getSize();
        // 自适应处理
        if (frameSize.height > screenSize.height)
        {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width)
        {
            frameSize.width = screenSize.width;
        }
        setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        addMenu();
        addButton();
        // 设定用户界面的外观
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch (Exception e)
        {
        }
        setResizable(false);
        setVisible(true);
        addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
        logMonitor.addObserver(this);
        excelDirText.setFocusable(false);
    }
    
    // Menu set
    private void addMenu()
    {
        JMenuBar mb = new JMenuBar();
        // 一级菜单
        JMenu conf = new JMenu(" 系 统 ");
        // 子菜单
        JMenuItem exit = new JMenuItem("退出");
        exit.addActionListener((ActionEvent event) -> System.exit(0));
        conf.add(exit);
        mb.add(conf);
        JMenu help = new JMenu(" 帮 助 ");
        JMenuItem about = new JMenuItem("关于工具");
        about.addActionListener(
            (ActionEvent event) -> JOptionPane.showMessageDialog(null, "Excel 数据库定义表生成处理工具 V1.0，00fly 于2018年3月。\n", "关于本工具", JOptionPane.INFORMATION_MESSAGE));
        help.add(about);
        mb.add(help);
        setJMenuBar(mb);
    }
    
    // JButton set
    private void addButton()
    {
        panel.setLayout(null);
        getContentPane().add(panel);
        logInfoLabel.setBounds(20, 10, 120, 18);
        panel.add(logInfoLabel);
        logInfoTextArea.setEditable(false);
        JScrollPane scroll = new JScrollPane(logInfoTextArea);
        // 分别设置水平和垂直滚动条自动出现
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setBounds(20, 30, 850, 360);
        panel.add(scroll);
        excelLabel.setBounds(30, 410, 240, 18);
        panel.add(excelLabel);
        excelDirText.setBounds(150, 410, 450, 24);
        excelDirText.setText(new File(" ").getAbsolutePath().trim());
        panel.add(excelDirText);
        excelDirBrowse.setBounds(610, 410, 80, 25);
        excelDirBrowse.setToolTipText("选择Excel数据库定义模板文件或目录，生成的sql文件也保存在此处");
        excelDirBrowse.addActionListener(event -> {
            String path = excelDirText.getText();
            File xmlfile = new File(path);
            if (new File(excelDirText.getText()).exists())
            {
                xmlfile = new File(path).getParentFile();
            }
            JFileChooser fc = new JFileChooser(xmlfile);
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.setDialogTitle("Excel 文件目录选择");
            if (fc.showOpenDialog(null) == 1)
            {
                return;
            }
            fc.setFileFilter(new FileFilter()
            {
                @Override
                public boolean accept(File file)
                {
                    return file.isDirectory() || file.getName().endsWith(".xlsx");
                }
                
                @Override
                public String getDescription()
                {
                    return ".xlsx";
                }
            });
            File f = fc.getSelectedFile();
            if (f.isDirectory())
            {
                excelDirText.setText(f.getAbsolutePath() + "\\");
            }
            else
            {
                excelDirText.setText(f.getAbsolutePath());
            }
        });
        panel.add(excelDirBrowse);
        export.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                if (!export.isEnabled())
                {
                    return;
                }
                export.setEnabled(false);
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                sqlParseUtil = new SQLParseUtil();
                sqlParseUtil.setLogMonitor(logMonitor);
                sqlParseUtil.setPath(excelDirText.getText());
                sqlParseUtil.execute();
            }
        });
        export.setBounds(250, 450, 160, 30);
        panel.add(export);
        clearLog.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                logInfoTextArea.setText(null);
            }
        });
        clearLog.setBounds(500, 450, 160, 30);
        panel.add(clearLog);
    }
    
    @Override
    public void update(Observable obj, Object msg)
    {
        if (msg instanceof String)
        {
            logInfoTextArea.append(msg.toString());
        }
        int length = logInfoTextArea.getText().length();
        logInfoTextArea.setCaretPosition(length);
        if (msg.toString().contains("处理完成"))
        {
            setCursor(null);
            export.setEnabled(true);
            // 打开生成的sql文件目录
            if (msg.toString().contains("文件处理完成")
                && JOptionPane.showConfirmDialog(panel, "SQL文件创建结束，是否立即查看文件信息？", "请确认", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
                try
                {
                    File file = new File(excelDirText.getText());
                    if (file.isFile())
                    {
                        file = file.getParentFile();
                    }
                    Desktop.getDesktop().open(file);
                }
                catch (IOException e)
                {
                }
            }
        }
    }
    
    // Run
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() -> new DataBaseUI());
    }
}
